import createStore, {} from 'ipreact-for-react'
import { DBKey, PermissionKey, User, UserPermission, UserRole } from '../server/interface'
import { api_permission, api_role } from './apis';

export interface IStoreState {
    loginUser: User | undefined;
    perm_map: Map<DBKey, UserPermission>;
    role_map: Map<DBKey, UserRole>;
    location_search: URLSearchParams;
}

const { connect, dispatch, getState } = createStore<IStoreState>()({
    loginUser: undefined,
    perm_map: new Map(),
    role_map: new Map(),
    location_search: new URLSearchParams(window.location.search),
})

export { connect, dispatch, getState }

export const hasPermission = (permissionKey: PermissionKey) => {
    const { loginUser } = getState();
    return loginUser?.permissions?.has(permissionKey);
}

export const updatePermission = async () => {
    if (hasPermission(PermissionKey.RBAC_PERMISSION)) {
        const res = await api_permission.list({ pageSize: 99999 })
        dispatch(state => {
            const perm_map = res && res.success ? new Map(res?.data?.list?.map(d => [d.key, d])) : state.perm_map;
            return { ...state, perm_map };
        });
    }
}

export const updateRole = async () => {
    if (hasPermission(PermissionKey.RBAC_ROLE)) {
        const res = await api_role.list({ pageSize: 99999 })
        dispatch(state => {
            const role_map = res && res.success ? new Map(res?.data?.list?.map(d => [d.key, d])) : state.role_map;
            return { ...state, role_map };
        });
    }
}

export const changeSearch = (values: Record<string, string>, title: string) => {
    const { location_search } = getState();
    for (const [key, value] of Object.entries(values)) {
        if (!value) {
            location_search.delete(key);
        } else {
            location_search.set(key, value);
        }
    }
    history.pushState(null, title, `?${location_search.toString()}`);
    dispatch(state => {
        return {
            ...state,
            location_search: new URLSearchParams(location_search),
        };
    });
}

addEventListener('popstate', () => {
    dispatch(state => {
        return {
            ...state,
            location_search: new URLSearchParams(window.location.search),
        };
    });
})
